package com.ruoyi.aitcommon.config;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitapp.utils.APPRuntimeManager;
import com.ruoyi.aitapp.vo.UserRunTimeVO;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.LogUtils;
import com.ruoyi.aitcommon.utils.ObjUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * AIT自定义退出处理类 返回成功
 * 该类需要配置在 SecurityConfig 中
 */
@Configuration
public class AITLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;
    @Autowired
    private APPRuntimeManager appRuntimeManager;

    private String readRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    }

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        //AIT登出处理
        final String bodystr = readRequestBody(request);
        if(ObjUtils.isNotBlank(bodystr)){
            final JSONObject json = JSONObject.parseObject(bodystr);
            final String username = json.getString("username");
            //更新运行信息
            final UserRunTimeVO userInfo = appRuntimeManager.getUserInfo(username);
            if(userInfo!=null){
                userInfo.setStatus(1);
                userInfo.setLogoutTime(DateUtil.date().toString());
                appRuntimeManager.updateUserInfo(userInfo);
                LogUtils.info("登录信息:AIT登出成功,用户[{}]",username);
            }
        }
        //若依登出处理
        logoutSuccessHandler.onLogoutSuccess(request, response, authentication);
    }
}
